package com.example.financialsystem.adapter;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.example.financialsystem.R;

import java.text.SimpleDateFormat;
import java.util.List;

import models.Record;

import static others.Const.currentIdAndNameHashTable;
import static others.Const.currentUserVo;

public class RecordAdapter extends ArrayAdapter<Record> {

    private int resourceId;

    public RecordAdapter(Context context, int resource, List<Record> objects) {
        super(context, resource, objects);
        resourceId = resource;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Record record = getItem(position);
        View view;
        ViewHolder viewHolder;
        if (convertView == null){
            view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
            viewHolder = new ViewHolder();
            viewHolder.recordClass = (TextView)view.findViewById(R.id.record_class);
            viewHolder.recordMoney = (TextView)view.findViewById(R.id.record_money);
            viewHolder.recordInformation = (TextView)view.findViewById(R.id.record_information);
            viewHolder.recordBelong = (TextView)view.findViewById(R.id.record_belong);
            view.setTag(viewHolder);
        }else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }

        viewHolder.recordClass.setText(record.getSecondclass());
        viewHolder.recordMoney.setText(record.getMoney()+"");
        if (record.getType() == 0){
            viewHolder.recordMoney.setTextColor(Color.GREEN);
        }else {
            viewHolder.recordMoney.setTextColor(Color.RED);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
        String info = sdf.format(record.getUpdatetime().getTime())+" · "+record.getSecondaccount();
        viewHolder.recordInformation.setText(info);
        if (currentUserVo.getId().equals(record.getUserid())){
            viewHolder.recordBelong.setVisibility(View.GONE);
        } else {
            String name = currentIdAndNameHashTable.get(record.getUserid());
            if (name != null){
                viewHolder.recordBelong.setText(name);
            } else {
                viewHolder.recordBelong.setText("未知用户");
            }
        }
        return view;
    }

    class ViewHolder{
        TextView recordClass;
        TextView recordMoney;
        TextView recordInformation;
        TextView recordBelong;
    }
}
